package com.xlf.service.system.controller.system;
import cn.hutool.core.bean.BeanUtil;
import com.xlf.common.auth.dao.UserDetailsImpl;
import com.xlf.common.auth.util.SecurityUtils;
import com.xlf.common.core.annotation.Anonymous;
import com.xlf.common.core.annotation.InnerAuth;
import com.xlf.common.core.constant.UserConstants;
import com.xlf.common.core.pojo.mode.AjaxResult;
import com.xlf.common.core.pojo.mode.BaseController;

import com.xlf.common.core.pojo.mode.R;
import com.xlf.common.core.pojo.vo.UserVO;
import com.xlf.common.core.util.BeanCopyUtils;
import com.xlf.common.core.util.StringUtils;
import com.xlf.common.core.util.page.TableDataInfo;
import com.xlf.pojo.system.SysRole;
import com.xlf.pojo.system.SysUser;

import com.xlf.service.system.service.SysRoleService;
import com.xlf.service.system.service.SysUserService;
import com.xlf.service.system.service.impl.SysPermissionService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.OpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息

 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPermissionService permissionService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }



    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {

    }

    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
       return error("未开发");
    }


    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {

        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        //拿所有角色
        List<SysRole> roles = roleService.selectRoleAll();
        //如果是管理员拿全部角色，如果不是排除掉管理员角色
        ajax.put("roles", SysUser.admin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
         if (StringUtils.isNotNull(userId))
        {
            //通过id拿用户
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user)))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user)))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.admin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        //管理员可以授权，
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取用户详情信息
     * 内部调用
     */
    @Anonymous
    @InnerAuth
    @GetMapping("/inner/userDetails")
    public R<UserDetailsImpl> getUserDetails(String username,String userId,String email)
    {

        SysUser sysUser = userService.selectUser(username, userId, email);

        if (StringUtils.isNull(sysUser))
        {
            return R.ok(null);
        }
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        UserDetailsImpl sysUserVo = new UserDetailsImpl();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取用户信息
     * 内部调用
     */
    @Anonymous
    @InnerAuth
    @GetMapping("/inner/userVO")
    public R<UserVO> getUserVO(String username, String userId, String email)
    {

        SysUser sysUser = userService.selectUser(username, userId, email);
        if (StringUtils.isNull(sysUser))
        {
            return R.ok(null);
        }

        return R.ok(BeanCopyUtils.copyObject(sysUser, UserVO.class));
    }

    /**
     * 通过ids获取用户信息
     * 内部调用
     */
    @PostMapping("/inner/userVOS")
    @InnerAuth
    @Anonymous
    public R<List<UserVO>> getUserById(@RequestBody Set<String> ids)
    {
        List<SysUser> users = Optional.ofNullable(userService.getUsersByIds(ids)).orElse(new ArrayList<>());
        return R.ok(BeanCopyUtils.copyList(users, UserVO.class));
    }


    /**
     * 新增用户
     * 内部调用
     */
    @PostMapping("/inner/addUser")
    @InnerAuth
    @Anonymous
    public R addUser(@RequestBody SysUser user)
    {
        try {
            userService.register(user);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 修改用户
     * 内部调用
     */
    @PostMapping("/inner/update")
    @InnerAuth
    @Anonymous
    public R updateUser(@RequestBody SysUser user){

        if(userService.updateById(user))
            return R.ok();
        return R.fail("更新用户信息失败");
    }

    /**
     * 获取用户信息
     */
    @Anonymous
    @InnerAuth
    @PostMapping("/inner/getUserInfo")
    public R<List<UserVO>> getUserInfo(@RequestBody SysUser user)
    {
        List<SysUser> list = Optional.ofNullable(userService.selectUserList(user)).orElse(new ArrayList<>());
        List<UserVO> userVOS = BeanUtil.copyToList(list, UserVO.class);

        return R.ok(userVOS);
    }

}
